package com.gan.simple_init.controller;

import com.gan.simple_init.common.constant.UserConstant;
import com.gan.simple_init.common.exception.BusinessException;
import com.gan.simple_init.common.base.ResponseErrorEnum;
import com.gan.simple_init.common.base.ResponseResult;
import com.gan.simple_init.common.base.RestResultGenerator;
import com.gan.simple_init.model.user.dto.UserLoginDTO;
import com.gan.simple_init.model.user.dto.UserUpdateDTO;
import com.gan.simple_init.model.user.entity.SysUser;
import com.gan.simple_init.service.SysUserService;
import com.gan.simple_init.util.JwtTokenUtil;
import com.gan.simple_init.util.UserCacheUtil;
import com.ramostear.captcha.HappyCaptcha;
import com.ramostear.captcha.support.CaptchaType;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author gbw
 * @date 2023/8/9
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    SysUserService sysUserService;

    @Resource
    JwtTokenUtil jwtTokenUtil;

    @Resource
    UserCacheUtil userCacheUtil;

    /**
     * 注册功能
     *
     * @param userLoginDTO
     * @return
     */
    @ApiOperation("注册")
    @PostMapping("/register")
    public ResponseResult<?> register(UserLoginDTO userLoginDTO) {
        return sysUserService.register(userLoginDTO);
    }


    /**
     * 修改用户信息
     *
     * @param userUpdateDTO
     * @return
     */
    @ApiOperation("修改用户信息")
    @PostMapping("/updateUserInfo")
    public ResponseResult<?> updateUserInfo(UserUpdateDTO userUpdateDTO) {
        if (userUpdateDTO == null || userUpdateDTO.getId() == null){
            throw new BusinessException(ResponseErrorEnum.ILLEGAL_PARAMS);
        }
        if (!userUpdateDTO.getUserName().matches(UserConstant.REGEX_USER_NAME)){
            throw new BusinessException("用户名不合法!");
        }
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userUpdateDTO,user);
        boolean res = sysUserService.updateById(user);
        if (!res){
            return RestResultGenerator.error("修改错误!");
        }
        return RestResultGenerator.success("修改成功!");
    }


    /**
     * 自定义security登录
     *
     * @param httpServletRequest
     * @param userLoginDTO
     * @return
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public ResponseResult<?> userLogin(HttpServletRequest httpServletRequest,@RequestBody UserLoginDTO userLoginDTO){
        return sysUserService.login(httpServletRequest,userLoginDTO);
    }

    /**
     * 自定义security登出
     *
     * @param request http请求
     * @return ResponseResult<?>
     */
    @ApiOperation("登出")
    @PostMapping("/logout")
    public ResponseResult<?> userLogout(HttpServletRequest request) {
        // 清除redis中对应的token
        jwtTokenUtil.removeRedisToken(request);
        return RestResultGenerator.success("登出成功!");
    }

    /**
     * 获取登录验证码
     *
     * @return ResponseResult<?>
     */
    @ApiOperation("获取登录验证码")
    @GetMapping("/verificationCode/get")
    public ResponseResult<?> getVerificationCode(HttpServletRequest request, HttpServletResponse response) {
        try {
            HappyCaptcha.require(request, response).type(CaptchaType.NUMBER).length(4).build().finish();
        } catch (Exception e) {
            log.error("error {}", e.getMessage(), e);
            return RestResultGenerator.error("获取验证码失败!");
        }
        return RestResultGenerator.success("获取验证码成功!");
    }

    /**
     * 校验登录验证码
     *
     * @return ResponseResult<?>
     */
    @ApiOperation("校验登录验证码")
    @GetMapping("/verificationCode/verify")
    public ResponseResult<?> verifyVerificationCode(String code, HttpServletRequest request) {
        try {
            boolean flag = HappyCaptcha.verification(request, code, true);
            if (flag) {
                //从session中移除
                HappyCaptcha.remove(request);
                return RestResultGenerator.success("校验验证码成功!");
            } else {
                return RestResultGenerator.error("验证码错误!");
            }
        } catch (Exception e) {
            log.error("error {}", e.getMessage(), e);
            return RestResultGenerator.error("校验验证码失败!");
        }
    }

    /**
     * 注销/删除用户
     *
     * @return ResponseResult<?>
     */
    @ApiOperation("删除用户")
    @PostMapping("/delete")
    public ResponseResult<?> deleteUser(@ApiParam(required = true) Long userId) {
        // 权限校验
        if (userCacheUtil.getUserId() != userId || !userCacheUtil.isAdmin()){
            throw new BusinessException(ResponseErrorEnum.USER_NO_PERMISSION);
        }
        if (sysUserService.getBaseMapper().deleteById(userId) > 0){
            return RestResultGenerator.success("删除成功!");
        } else {
            return RestResultGenerator.success("删除失败!");
        }
    }

    /**
     * 刷新token
     *
     * @return ResponseResult<?>
     */
    @ApiOperation("刷新token")
    @PostMapping("/refresh_token")
    public ResponseResult<?> refreshToken(HttpServletRequest request) {
        return sysUserService.refreshToken(request);
    }
}
